/******************************************************************************
 * @File name   :      MaintainActivateController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 31, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 31, 2015 2:06:59 PM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.activation.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.activation.dto.ActivationQueryDto;
import com.cap.bts.crmdp.dealer.activation.dto.ActivationResultsDto;
import com.cap.bts.crmdp.dealer.activation.service.IActivationService;
import com.cap.bts.crmdp.dealer.coupon.domain.Ticket;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.member.service.IMaintainCarPlateService;
import com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService;
import com.cap.bts.crmdp.dealer.packagegift.service.IMemberGiftService;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.purchase.domain.PackageDefinition;
import com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;

/**
 * 
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/activation")
public class MaintainActivationController extends BaseController {

	static final String GETMEMBERACTIVATIONPAGE = "getMemberActivationPage";

	private static final  Logger LOGGER  = Logger.getLogger(MaintainActivationController.class);
	@Autowired
	IActivationService activationService;
	@Autowired
	IMemberGiftService memberGiftService;
	
    @Autowired
    IMaintainCarPlateService  maintainCarPlateService;
    
    @Autowired
    IMaintainMemberService maintainMemberService;
    
    @Autowired
    IMarsMemberPackageService memberPackageService;
	
	/**
	 * 
	 * @Date : 2015-7-20
	 * @param dto
	 *            MemberResultsDto
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value = "/toGetMemberActivationPage")
	public String getMemberActivationPage(MemberResultsDto dto, Model model, HttpServletRequest request) throws AppException{
		
		ActivationResultsDto activationResultsDto = new ActivationResultsDto();
		if(dto != null){
			activationResultsDto.setMemberId(dto.getId());
			try {
                activationResultsDto.setCarPlate(java.net.URLDecoder.decode(dto.getCarPlate(), "UTF-8"));
                activationResultsDto.setMemberName(java.net.URLDecoder.decode(dto.getMemberName(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new AppException("getMemberActivationPage",e);
            }
			activationResultsDto.setMobilePhone(dto.getMobilePhone());
		}
		
		request.getSession().setAttribute(GETMEMBERACTIVATIONPAGE, activationResultsDto);
		model.addAttribute("activationResultsDto", activationResultsDto);
		model.addAttribute("dto", activationResultsDto);
		MemberQueryDto memberQueryDto = (MemberQueryDto) request.getSession().getAttribute("getMaintainMemberPage");
		if(memberQueryDto != null && dto != null){
		    memberQueryDto.setIsSelected("radio"+ dto.getId() +activationResultsDto.getCarPlate() +"Rad");
		}
		return "/activation/activation";
	}
	

	/**
	 * 
	 * @Date : 2015-7-20
	 * @param dto
	 *            MemberPackageInfoSubmitDto
	 * @param model
	 *            Model
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/toSaveMemberActivation")
	public Map<String,Object> saveMemberActivation(MemberPackageInfoSubmitDto dto, Model model, HttpServletRequest request) throws AppException {
		Map<String,Object> rtnMap=new HashMap<String, Object>();
	    try {
	        boolean isAfterPurchase=false;
	        if(dto.getPackageDefId()==null){
	            isAfterPurchase=true;
	        }
	        
			dto.setDealerId(UserUtil.getCurrentUser().getDealerId());
			List<PackageDefinition> list=memberGiftService.getPackageGiftListInfo(dto);
			StringBuilder successMsg=new StringBuilder();
			if(list!=null&&!list.isEmpty()){
			    successMsg.append("套餐:");
			   for (Iterator<PackageDefinition> iterator = list.iterator(); iterator.hasNext();) {
			       PackageDefinition packageDefinition = (PackageDefinition) iterator.next();
			       successMsg.append(packageDefinition.getName()+",");
			   }
			}
			
			List<Ticket> listTicket=memberGiftService.getTicketGiftListInfo(dto);
            if(listTicket!=null&&!listTicket.isEmpty()){
               for (Iterator<Ticket> iterator = listTicket.iterator(); iterator.hasNext();) {
                   Ticket t = (Ticket) iterator.next();
                   if("COUPON".equals(t.getTicketType())){
                       successMsg.append("优惠券:");
                   }else {
                       successMsg.append("提货券:");
                   }
                   successMsg.append(t.getTicketName()+",");
               }
            }
            if(!successMsg.toString().isEmpty()){
                successMsg.append("已赠送！");
                rtnMap.put("successMsg",successMsg.toString());
            }else{
                rtnMap.put("successMsg","激活成功 ！");
            }
            if(isAfterPurchase){
                dto.setPackageDefId(null);
            }
			activationService.saveMemberPurchaseAndActivationNow(dto);
		} catch (AppException e) {
		    LOGGER.error("saveMemberActivation",e);
			rtnMap.put("errorMsg",e.getMessage());
		}
		return rtnMap;
	}
	
	
	/**
     * 
     * @Date : 2015-7-20
     * @param MemberResultsDto
     *            String
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/isPackageNumberExist")
    public Map<String,Object> isPackageNumberExist(MemberResultsDto dto,Model model, HttpServletRequest request) throws AppException {
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        ActivationQueryDto aqd = new ActivationQueryDto();
        aqd.setPackageNumber(dto.getPackageNumber());
        MemberPackageInfo cmpi =null;
        if(dto.getPackageNumber()!=null &&!"".equals(dto.getPackageNumber())){
            cmpi=activationService.checkPackageNumberByActivationDto(aqd);
            if(cmpi==null){
                rtnMap.put("error", "该卡号不存在!");
                rtnMap.put("success", false);
            }else {
                if(cmpi.getPurchaseDate()!=null){
                    rtnMap.put("success", true);
                }else{
                    rtnMap.put("error", "该卡号尚未购买！");
                    rtnMap.put("success", false);
                }
            }
           
        }else{
            rtnMap.put("error", "卡号不能为空!");
            rtnMap.put("success", false);
        }
       
        return rtnMap;
    }
    
    /**
     * 
     * @Date : 2015-7-20
     * @param dto
     *            MemberResultsDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @throws AppException
     */
    @RequestMapping(value = "/toPurchaseDetailInfo")
    public String toPurchaseDetailInfo(String packageNumber, Model model, HttpServletRequest request) throws AppException{
        ActivationQueryDto aqd = new ActivationQueryDto();
        aqd.setPackageNumber(packageNumber);
        MemberPackageInfo cmpi = activationService.checkPackageNumberByActivationDto(aqd);
        MemberInfo mi=null;
        CarPlateInfo cpi=null;
        if(cmpi!=null){
            aqd.setPrice(cmpi.getActualPrice());
            aqd.setPurchaseDate(cmpi.getPurchaseDate());
            if(cmpi.getActiveDate()!=null){
                aqd.setIsActived(true);
            }else{
                aqd.setIsActived(false);
            }
            aqd.setPackageName(cmpi.getPackageDefinition().getName());
            aqd.setCardName(cmpi.getCardDefinition().getName());
            mi= maintainMemberService.getMemberById(cmpi.getMemberId());
            cpi=maintainCarPlateService.getCarPlateInfoById(cmpi.getCarId());
            aqd.setDealerId(cmpi.getDealerId().toString());
        }
        if(mi!=null){
            aqd.setMemberName(mi.getMemberName());
            aqd.setMobilePhone(mi.getMobilePhone());
        }
        if(cpi!=null){
            aqd.setCarPlate(cpi.getCarPlate());
        }
        aqd.setPackageNumber(packageNumber);
        model.addAttribute("dto", aqd);
        
        return  "/activation/purchaseDetailInfo";
    }
}
